import axiosConfig from './axios.config';
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';

export const get = (url: string, params?: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    filterParams(params);
    axiosConfig.get(url, { params }).then(res => resolve(res)).catch(err => reject(err));
  });
};

export const post = (url: string, data?: any, params?: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    axiosConfig.post(url, data, {
      params,
      headers: {
        'Content-Type': data ? 'application/json;charset=UTF-8' : 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    }).then(res => resolve(res)).catch(err => reject(err));
  });
};

export const deleted = (url: string, params?: any): Promise<any> => {
  filterParams(params);
  return new Promise((resolve, reject) => {
    axiosConfig.delete(url, { params }).then(res => resolve(res)).catch(err => reject(err));
  });
};

const filterParams = (params: any): void => {
  if (params) {
    Object.keys(params).forEach(item => {
      if (params[item] === '') delete params[item];
    });
  }
};

export const get1 = (url: string, params?: any, headers?: any): Promise<any> => {
  console.log(1, params, 2, headers);

  return new Promise((resolve, reject) => {
    filterParams(params);
    axiosConfig.get(url, { params, headers }).then(res => resolve(res)).catch(err => reject(err));
  });
};

export const getQueryVariable=(variable:any)=>{
  var arr = window.location.href.split('?')
  var paramsMap = new Map()
  // console.log(window.location,'window.location');
  if (arr.length <= 1) return '';
    var vars = arr[1].split('&')
    for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            var key =pair[0].trim();
            var value = pair[1].trim();
            paramsMap.set(key,value)
    }
  return paramsMap.get(variable)
}